package com.beamfield.common;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;

import com.beamfield.model.FileInfo;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.apache.commons.lang3.math.NumberUtils;

public class CommonUtils {

	/**
	 * 读取配置文件
	 */
	public static Properties properties = new Properties();

	static {
		try {
			String path = "config.properties";
			InputStream inStream = CommonUtils.class.getClassLoader().getResourceAsStream(path);
			if (inStream == null) {
				inStream = CommonUtils.class.getClassLoader().getResourceAsStream("/" + path);
			}
			properties.load(inStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 工程访问路径
	public static String getWebRootUrl() {
		return properties.getProperty("webRootUrl");
	}

    private static Pattern HANZI = Pattern.compile("[\\u4E00-\\u9FBF]+");

	public static int getStrNum(String str){
		return Arrays.stream(Optional.ofNullable(str).orElse("").split("")).map(c->{
			if(NumberUtils.isDigits(c)){
				return Integer.parseInt(c);
			}else{
				return 0;
			}
		}).reduce(0, Integer::sum);
	}

	public static int getStrJoinNum(String str){
		String s = Arrays.stream(Optional.ofNullable(str).orElse("").split("")).map(c -> {
			if (NumberUtils.isDigits(c)) {
				return c;
			} else {
				return "";
			}
		}).collect(Collectors.joining(""));

		if(NumberUtils.isDigits(s)){
			return Integer.parseInt(s);
		}else{
			return 0;
		}
	}


	/**
     * 将汉字转为拼音
     * @param str
     * @return
     */
	public static String getPinYin(String str){
	    HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
	    outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
	    StringBuilder sb = new StringBuilder();
		for(int i=0; i < str.length(); i++){
			char word = str.charAt(i);
			if(!HANZI.matcher(String.valueOf(word)).matches()){
			    sb.append(word);
			    continue;
            }
            String[] pinyinArray = new String[0];
            try {
                pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word, outputFormat);
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                e.printStackTrace();
            }
            sb.append(pinyinArray[0]);
        }
        return sb.toString();
	}
	/**
	 * 获取汉字首字母
	 * @param str
	 * @return
	 */
	public static String getPinYinHeadChar(String str) {

		StringBuilder convert = new StringBuilder();
		for (int j = 0; j < str.length(); j++) {
			char word = str.charAt(j);
			// 提取汉字的首字母
			String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
			if (pinyinArray != null) {
				convert.append(pinyinArray[0].charAt(0));
			} else {
				convert.append(word);
			}
		}
		return convert.toString();
	}

	/**
	 * String -> long
	 *
	 * @param string
	 * @return long
	 */
	public static long parseLong(String string, long def) {
		if (isEmptyString(string)) {
			return def;
		}
		long num;
		try {
			num = Long.parseLong(string);
		} catch (Exception e) {
			num = def;
		}
		return num;
	}

	/**
	 * @param date
	 * @param string
	 * @return
	 */
	public static String getTimeFormat(Date date, String string) {
		SimpleDateFormat sdFormat;
		if (StringUtils.isBlank(string)) {
			sdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		} else {
			sdFormat = new SimpleDateFormat(string);
		}
		try {
			return sdFormat.format(date);
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 检查路径是否存在，不存在则创建路径
	 *
	 * @param path
	 */
	public static void checkPath(String path) {
		String[] paths = null;
		if (path.contains("/")) {
			paths = path.split(File.separator);
			System.out.println(paths);
		} else {
			paths = path.split(File.separator + File.separator);
		}
		if (paths == null || paths.length == 0) {
			return;
		}
		String pathdir = "";
		for (String string : paths) {
			pathdir = pathdir + string + File.separator;
			File file = new File(pathdir);
			if (!file.exists()) {
				file.mkdir();
			}
		}
	}
	public static byte[] getRequestPostBytes(HttpServletRequest request) throws IOException {
		int contentLength = request.getContentLength();
		if (contentLength < 0) {
			return null;
		} else {
			byte[] buffer = new byte[contentLength];

			int readlen;
			for(int i = 0; i < contentLength; i += readlen) {
				readlen = request.getInputStream().read(buffer, i, contentLength - i);
				if (readlen == -1) {
					break;
				}
			}

			return buffer;
		}
	}

	public static JSONObject getJsonObject(HttpServletRequest request) {
		try {
			JSONObject jsonObj = null;
			byte[] buffer = CommonUtils.getRequestPostBytes(request);
			String charEncoding = request.getCharacterEncoding();
			if (charEncoding == null) {
				charEncoding = "UTF-8";
			}

			String result = new String(buffer, charEncoding);
			jsonObj = JSON.parseObject(result);
			return jsonObj;
		} catch (Exception var5) {
			return null;
		}
	}

	public class Point {
		double x;
		double y;

		public Point() {
		}

		public Point(Double longitude, Double latitude) {
			this.x = longitude.doubleValue();
			this.y = latitude.doubleValue();
		}
	}

	/**
	 * MD5加密
	 *
	 * @param 要加密的String
	 * @return 加密后String(大写)
	 */
	public final static String MD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] strTemp = s.getBytes();
			// 使用MD5创建MessageDigest对象
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte b = md[i];
				str[k++] = hexDigits[b >> 4 & 0xf];
				str[k++] = hexDigits[b & 0xf];
			}
			return new String(str).toLowerCase();
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 返回一个点是否在一个多边形区域内
	 *
	 * @param mPoints
	 *            多边形坐标点列表
	 * @param point
	 *            待判断点
	 * @return true 多边形包含这个点,false 多边形未包含这个点。
	 */
	public static boolean isPolygonContainsPoint(List<Point> mPoints, Point point) {
		int nCross = 0;
		for (int i = 0; i < mPoints.size(); i++) {
			Point p1 = mPoints.get(i);
			Point p2 = mPoints.get((i + 1) % mPoints.size());
			// 取多边形任意一个边,做点point的水平延长线,求解与当前边的交点个数
			// p1p2是水平线段,要么没有交点,要么有无限个交点
			if (p1.y == p2.y) {
				continue;
			}
			// point 在p1p2 底部 --> 无交点
			if (point.y < Math.min(p1.y, p2.y)) {
				continue;
			}
			// point 在p1p2 顶部 --> 无交点
			if (point.y >= Math.max(p1.y, p2.y)) {
				continue;
			}
			// 求解 point点水平线与当前p1p2边的交点的 X 坐标
			double x = (point.y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x;
			if (x > point.x) // 当x=point.x时,说明point在p1p2线段上
			{
				nCross++; // 只统计单边交点
			}
		}
		// 单边交点为偶数，点在多边形之外 ---
		return (nCross % 2 == 1);
	}

	public static Date getDateFormat(String date, String format) {
		if (isEmptyString(date)) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			// System.out.println(sdf.parse(date));
			return sdf.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static boolean isEmptyString(String value) {
		if (value == null || value.length() == 0) {
			return true;
		}
		return false;
	}

	public static int parseInt(String string, int def) {
		if (isEmptyString(string)) {
			return def;
		}
		int num = def;
		try {
			num = Integer.parseInt(string);
		} catch (Exception e) {
			num = def;
		}
		return num;
	}

	public static double parseDouble(String string, double def) {
		if (isEmptyString(string)) {
			return def;
		}
		double num = def;
		try {
			num = Double.parseDouble(string);
		} catch (Exception e) {
			num = def;
		}
		return num;
	}

	/**
	 * 获取请求所有参数
	 *
	 * @param request
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, Object> getAllParams(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Enumeration paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();

			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() != 0) {
					map.put(paramName, paramValue);
				}
			}
		}
		return map;
	};

	// 上传文件的目录
	public static String getLocationPath() {
		return properties.getProperty("uploadFilePath");
	}

	// 上传文件的临时目录
	public static String getUploadTempPath() {
		return properties.getProperty("uploadTempPath");
	}

	// 文件访问路径
	public static String getFileRootUrl() {
		return properties.getProperty("fileRootUrl");
	}

	// 生成四位随机数字验证码
	public static String getRandomVcode() {
		String str = "0123456789";
		StringBuilder sb = new StringBuilder(4);
		for (int i = 0; i < 4; i++) {
			char ch = str.charAt(new Random().nextInt(str.length()));
			sb.append(ch);
		}
		return sb.toString();
	}

	// 生成八位随机密码
	public static String getRandomPassword() {
		String str = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
		StringBuilder sb = new StringBuilder(8);
		for (int i = 0; i < 8; i++) {
			char ch = str.charAt(new Random().nextInt(str.length()));
			sb.append(ch);
		}
		return sb.toString();
	}

	public static String stringToHexString(String s) {
		String str = "";
		for (int i = 0; i < s.length(); i++) {
			int ch = (int) s.charAt(i);
			String s4 = Integer.toHexString(ch);
			// System.out.println(s4);
			str = str + s4;
		}
		return str;
	}

	public static String str2HexStr(String str) {
		char[] chars = "0123456789ABCDEF".toCharArray();
		StringBuilder sb = new StringBuilder("");
		byte[] bs = str.getBytes();
		int bit;
		for (int i = 0; i < bs.length; i++) {
			sb.append("0x");
			bit = (bs[i] & 0x0f0) >> 4;
			sb.append(chars[bit]);
			bit = bs[i] & 0x0f;
			// System.out.println(chars[bit]);
			sb.append(chars[bit]);
		}
		return sb.toString();
	}

	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	public static Object getfilerootUrl() {
		return properties.getProperty("filerootUrl");
	}

	/**
	 * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
	 *
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	public static String createSign(SortedMap<String, String> packageParams, String key) throws Exception {
		String sb = "";
		Set<Entry<String, String>> es = packageParams.entrySet();
		Iterator<Entry<String, String>> it = es.iterator();
		while (it.hasNext()) {
			Entry<String, String> entry = it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb += k + "=" + v + "&";
			}
		}
		return sb + "key=" + key;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 *
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 使用md5算法进行加密
	 *
	 * @param target
	 *            要加密的字符串
	 * @param charset
	 *            编码（请设置为UTF-8)
	 * @return 加密后的字符串
	 */
	public static String encryptWithMD5(String target, String charset) {
		String md5Str = null;
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.reset();
			byte[] bytes = md5.digest(charset == null ? target.getBytes() : target.getBytes(charset));
			StringBuffer stringBuffer = new StringBuffer();
			for (byte b : bytes) {
				int bt = b & 0xff;
				if (bt < 16) {
					stringBuffer.append(0);
				}
				stringBuffer.append(Integer.toHexString(bt));
			}
			md5Str = stringBuffer.toString();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return md5Str;
	}

	// 文件完整访问路径
	public static String getFielUrl(FileInfo fileInfo) {
		if(fileInfo == null){
			return "";
		}
		String url = "" + properties.getProperty("fileRootUrl") + fileInfo.getFile_path() + fileInfo.getOriginal_name();
		url = url.replace(File.separatorChar, '/');
		return url;
	}

	// 文件完整访问路径
		public static String getQrUrl(FileInfo fileInfo) {
		if(fileInfo == null){
			return "";
		}
			String url = "" + properties.getProperty("qrFileRootUrl") + fileInfo.getFile_path() + fileInfo.getOriginal_name();
			url = url.replace(File.separatorChar, '/');
			return url;
		}

	/**
	 * 发起https请求
	 *
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式（GET、POST）
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static JsonObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
		JsonObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象
			TrustManager[] tm = { (TrustManager) new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod)) {
				httpUrlConn.connect();
			}
			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 编码格式
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			JsonParser jp = new JsonParser();
			jsonObject = (JsonObject) jp.parse(buffer.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObject;
	}

	/**
	 * 获取当前时间 yyyyMMddHHmmss
	 *
	 * @return String
	 */
	public static String getCurrTime() {
		Date now = new Date();
		SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String s = outFormat.format(now);
		return s;
	}

	/**
	 * 取出一个指定长度大小的随机正整数.
	 *
	 * @param length
	 *            int 设定所取出随机数的长度。length小于11
	 * @return int 返回生成的随机数。
	 */
	public static int buildRandom(int length) {
		int num = 1;
		double random = Math.random();
		if (random < 0.1) {
			random = random + 0.1;
		}
		for (int i = 0; i < length; i++) {
			num = num * 10;
		}
		return (int) ((random * num));
	}

	/**
	 * 只判断多个String是否为空(无论有没全角或半角的空格) 若非空则返回true,否则返回false
	 *
	 * @param str
	 * @return boolean
	 */
	public static boolean isEmptyAllString(String... str) {
		if (null == str) {
			return true;
		}
		for (String s : str) {
			if (isEmptyString(s)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 检查是否缺少参数
	 *
	 * @param param
	 *            需要检查的为空的参数们
	 * @return true 缺少 false 不缺少
	 * @date 2018年6月11日
	 * @author mintonzhang@163.com
	 */
	public static boolean checkMissParam(Object... param) {
		if (param != null && param.length != 0) {
			int i=0;
			for (Object object : param) {
				if (object == null || "".equals(object) || object.toString().length() == 0) {
					System.out.println("缺少第"+i+"个参数,0开始");
					return true;
				}
				i++;
			}
		}
		return false;
	}

	/**
	 * 判断是否为空
	 *
	 * @param object
	 * @return
	 * @date 2018年6月11日
	 * @author mintonzhang@163.com
	 */
	@SuppressWarnings("unchecked")
	public static <T> T checkIsNull(T object, T def) {

		if (object instanceof List) {
			return (T) ((object == null || ((List<T>) object).size() == 0) ? def : ((List<T>) object).size());
		}

		if (object == null || StringUtils.isBlank((CharSequence) object)) {
			return def;
		}
		return (T) object;
	}

	/**
	 * 得到单个Map
	 * @date 2018年6月14日
	 * @author mintonzhang@163.com
	 * @param key
	 * @param value
	 * @return
	 */
	public static <K, V> Map<K, V> getHashMap(K key, V value) {
		Map<K, V> hashMap = new HashMap<K, V>();
		hashMap.put(key, value);
		return hashMap;

	}

	/**
	 * 分页
	 *
	 * @author minton
	 * @param <T>
	 * @email mintonzhang@163.com
	 * @date 2018年5月29日
	 * @param pageIndexStr
	 * @param pageSizeStr
	 * @param defaultSize
	 * @param data
	 * @return
	 */
	public static <T> List<T> getPageInfoResult(String pageIndexStr, String pageSizeStr, int defaultSize, List<T> data) {
		int pageIndex = 0;
		int pageSize = defaultSize;
		if (StringUtils.isNotBlank(pageIndexStr)&&!"0".equals(pageIndexStr)) {
			pageIndex = Integer.valueOf(pageIndexStr) - 1;
		}
		if (StringUtils.isNotBlank(pageSizeStr)) {
			pageSize = Integer.valueOf(pageSizeStr);
		}
		int indexFrom = pageIndex * pageSize;
		int indexTo = (pageIndex + 1) * pageSize;
		if (indexTo >= data.size()) {
			indexTo = data.size();
		}
		if (indexFrom >= indexTo) {
			return new ArrayList<>();
		}
		return data.subList(indexFrom, indexTo);
	}

	/**
	 * 生成二维码（无边框）
	 * @date 2018年6月15日
	 * @author mintonzhang@163.com
	 * @param content
	 * @return 产生的文件名称
	 * @throws IOException
	 * @throws WriterException
	 */
	public static String createQrcode(String savePath,String content) {
		try {
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();

			hints.put(EncodeHintType.MARGIN, 0);

			BitMatrix bitMatrix = new QRCodeWriter().encode(content,BarcodeFormat.QR_CODE, 256, 256,hints);

			//1.1去白边
			int[] rec = bitMatrix.getEnclosingRectangle();

			int resWidth = rec[2] + 1;

			int resHeight = rec[3] + 1;

			BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);

			resMatrix.clear();

			for (int i = 0; i < resWidth; i++) {

			    for (int j = 0; j < resHeight; j++) {

			        if (bitMatrix.get(i + rec[0], j + rec[1])) {

			             resMatrix.set(i, j);
			        }
			    }
			}
			int width = resMatrix.getWidth();

			int height = resMatrix.getHeight();

			BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_ARGB);

			for (int x = 0; x < width; x++) {

			    for (int y = 0; y < height; y++) {

			        image.setRGB(x, y, resMatrix.get(x, y) == true ?

			        Color.BLACK.getRGB():Color.WHITE.getRGB());
			    }
			}
			//3

			// 定义上传路径
			CommonUtils.checkPath(properties.getProperty("uploadFilePath") + savePath);
			String myFileName = getTimeFormat(new Date(), "yyyyMMddhhmmssSSS") + "_"
					+ (int) (Math.random() * 100) + ".png";
			File localOriginFile = new File(properties.getProperty("uploadFilePath") + savePath + myFileName);
			ImageIO.write(image,"png", localOriginFile);
			return myFileName;
		}catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 判断是否为数字（包括浮点）
	 * @param str
	 * @return
	 */
	public static boolean isNumber(String str){
		String reg = "^[0-9]+(.[0-9]+)?$";
		return str.matches(reg);
	}

	/**
	 * 获取两个日期之间的所有日期(包含边界日期)
	 */
	public static List<Date> getBetweenDates(Date begin, Date end) {
		List<Date> result = new ArrayList<Date>();
		Calendar tempStart = Calendar.getInstance();
		tempStart.setTime(begin);
		while(begin.getTime()<=end.getTime()){
			result.add(tempStart.getTime());
			tempStart.add(Calendar.DAY_OF_YEAR, 1);
			begin = tempStart.getTime();
		}
		return result;
	}
	/**
	 * date to localDate
	 * @param date
	 * @return
	 */
	public static LocalDate toLocalDate(Date date){
		Instant instant = date.toInstant();
		ZoneId zoneId = ZoneId.systemDefault();
		ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, zoneId);
		return zonedDateTime.toLocalDate();
	}
}
